/****************************************************************************
 Copyright (c) 2017-2020 SuperSuRaccoon
 
 Site: http://www.supersuraccoon-cocos2d.com
 Mail: supersuraccoon@gmail.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var ssr = ssr || {};

ssr.EditableGeometryNode = cc.Node.extend({
    ctor:function(vertexArray) {
        this._super();
        this._init(vertexArray);
        this._update();
        this._render();
        //
        this._delegate = null;
        this.enableTouch();
        this.setValidateTouchCallback(this.delegateValidateTouchInNode);
    },
    _init:function(vertexArray) {
        this._vertexArray = vertexArray;
        this._renderColor = cc.color.WHITE;
        this._isDebugDrawOn = false;
        this._renderNode = new cc.DrawNode();
        this.addChild(this._renderNode);
        this.setAnchorPoint(0.5, 0.5);
    },
    /* 
        根据 vertexArray 设置 position, contentSize
    */
    _update:function() {
        this._isVertexUpdated = true;
        //
        var l = this._vertexArray[0].x;
        var r = this._vertexArray[0].x;
        var t = this._vertexArray[0].y;
        var b = this._vertexArray[0].y;

        for (var i = 1; i < this._vertexArray.length; i ++) {
            if (this._vertexArray[i].x < l) {
                l = this._vertexArray[i].x;
            }
            if (this._vertexArray[i].x > r) {
                r = this._vertexArray[i].x;
            }
            if (this._vertexArray[i].y < b) {
                b = this._vertexArray[i].y;
            }
            if (this._vertexArray[i].y > t) {
                t = this._vertexArray[i].y;
            }
        }
        this.setContentSize((r - l), (t - b));
        this.setPosition(l + (r - l) * this.getAnchorPoint().x, b + (t - b) * this.getAnchorPoint().y);
    },
    /* 
        渲染多边形
        只需要在顶点发生变化和位置发生变化的时候调用，任何形变都不需要调用
    */
    _render:function() {
        // need override
    },
    /* 
        获取顶点数组
        所有顶点坐标都进行过矩阵变换计算
    */
    getVertexArray:function() {
        // need override  
    },
    /* 
        获取顶点数组
        所有顶点坐标都没有进行过矩阵变换计算，是原始数组
    */
    getRawVertexArray:function() {
        // need override
    },
    addVertex:function(vertex) {
        this._vertexArray.push(vertex);
        this._update();
        this._render();
    },
    removeVertex:function(index) {
        if (this._vertexArray[index] === undefined) {
            return;
        }
        this._vertexArray.splice(index, 1);
        this._update();
        this._render();
    },
    updateVertex:function(index, vertex) {
        if (this._vertexArray[index] === undefined) {
            return;
        }
        this._vertexArray[index] = vertex;
        this._update();
        this._render();
    },
    _updateInNodeVertexArray:function() {
        this._inNodeVertextArray = [];
        var x = this.getPositionX();
        var y = this.getPositionY();
        var w = this.getContentSize().width * this.getAnchorPoint().x;
        var h = this.getContentSize().height * this.getAnchorPoint().y;
        for (var i = 0; i < this._vertexArray.length; i ++) {
            this._inNodeVertextArray.push(cc.p(this._vertexArray[i].x - x + w, this._vertexArray[i].y - y + h));
        }
    },
    _updateTransformedVertexArray:function() {
        this._transformedVertexArray = [];
        var anAffineTransform = this.getNodeToParentTransform();
        for (var i = 0; i < this._inNodeVertextArray.length; i ++) {
            var transformed = cc.pointApplyAffineTransform(this._inNodeVertextArray[i], anAffineTransform);
            this._transformedVertexArray.push(transformed);
        }
    },
    setColor:function(color) {
        this._super(color);
        this._renderColor = color;
        this._render();
    },
    setRotation:function(newRotation) {
        cc.Node.prototype.setRotation.call(this, newRotation);
        this._updateTransformedVertexArray();
    },
    setRotationX:function(rotationX) {
        cc.Node.prototype.setRotationX.call(this, rotationX);
        this._updateTransformedVertexArray();
    },
    setRotationY:function(rotationY) {
        cc.Node.prototype.setRotationY.call(this, rotationY);
        this._updateTransformedVertexArray();
    },
    setScale:function(scale, scaleY) {
        cc.Node.prototype.setScale.apply(this, arguments);
        this._updateTransformedVertexArray();
    },
    setScaleX:function(newScaleX) {
        cc.Node.prototype.setScaleX.call(this, newScaleX);
        this._updateTransformedVertexArray();
    },
    setScaleY:function(newScaleY) {
        cc.Node.prototype.setScaleY.call(this, newScaleY);
        this._updateTransformedVertexArray();
    },
    setPosition:function(newPosOrxValue, yValue) {
        this.__oldPosition = cc.p(this.getPosition());
        cc.Node.prototype.setPosition.apply(this, arguments);
        this._updateVertexArray();
        this._updateInNodeVertexArray();
        this._updateTransformedVertexArray();
        this.__oldPosition = cc.p(this.getPosition());
    },
    setPositionX:function(x) {
        this.__oldPosition = cc.p(this.getPosition());
        cc.Node.prototype.setPositionX.call(this, x);
        this._updateVertexArray();
        this._updateInNodeVertexArray();
        this._updateTransformedVertexArray();
    },
    setPositionY:function(y) {
        this.__oldPosition = cc.p(this.getPosition());
        cc.Node.prototype.setPositionY.call(this, y);
        this._updateVertexArray();
        this._updateInNodeVertexArray();
        this._updateTransformedVertexArray();
    },
    setAnchorPoint:function(point, y) {
        var validAnchorPoint = true;
        if (y === undefined) {
            if (point.x != 0.5 || point.y != 0.5) {
                validAnchorPoint = false;
                cc.error("anchor point must be cc.p(0.5, 0.5)");
            }    
        } 
        else {
            if (point != 0.5 || y != 0.5) {
                validAnchorPoint = false;
                cc.error("anchor point must be cc.p(0.5, 0.5)");
            }  
        }
        if (validAnchorPoint) {
            cc.Node.prototype.setAnchorPoint.apply(this, arguments);
        }
    },
    setDelegate:function(delegate) {
        this._delegate = delegate;
    },
    _updateVertexArray:function() {
        if (this._isVertexUpdated) {
            this._isVertexUpdated = false;
            return;
        }
        var x = this.getPositionX() - this.__oldPosition.x;
        var y = this.getPositionY() - this.__oldPosition.y;
        if (x == 0 && y == 0) {
            return;
        }
        for (var i = 0; i < this._vertexArray.length; i ++) {
            this._vertexArray[i] = cc.p(this._vertexArray[i].x + x, this._vertexArray[i].y + y);
        }
    },
    _getVertexIndexFromTouch:function(touchLocation) {
        this._updateTransformedVertexArray();
        var nodeLocation = touchLocation;
        var vertexIndex = -1;
        for (var i = 0; i < this._transformedVertexArray.length; i ++) {
            if (cc.pDistance(this._transformedVertexArray[i], nodeLocation) < 10) {
                vertexIndex = i;
                break;
            }
        }
        return vertexIndex;
    },
    _invertTransformedPosition:function(position) {
        var anAffineTransform = cc.affineTransformInvert(this.getNodeToParentTransform());
        var invert = cc.pointApplyAffineTransform(position, anAffineTransform);
        return cc.p(
            invert.x + this.getPositionX() - this.getContentSize().width * this.getAnchorPoint().x,
            invert.y + this.getPositionY() - this.getContentSize().height * this.getAnchorPoint().y
        );
    }, 
    delegateValidateTouchInNode:function(touchLocation) {
        var nodeLocation = this.convertToNodeSpaceAR(touchLocation); 
        var inflate = 4;
        var rect = new cc.rect(
            - this.getContentSize().width / 2 - inflate,
            - this.getContentSize().height / 2 - inflate,
            this.getContentSize().width + inflate * 2,
            this.getContentSize().height + inflate * 2
        );
        return cc.rectContainsPoint(rect, nodeLocation);
    },
    delegateTouchBegan:function(touch, event) {
        if (!this.isSelected()) {
            return;
        }

        var location = touch.getLocation();
        var nodeLocation = this.convertToNodeSpaceAR(location); 
        this._editGrabPosition = nodeLocation;

        var selectedVertexIndex = this._getVertexIndexFromTouch(location);
        if (selectedVertexIndex != -1) {
            this._isEditVertex = true;
            this._editVertexIndex = selectedVertexIndex;
        }
        if (!this._isEditVertex) {
            var inflate = 6;
            var rotatingConnerArray = [
                cc.p(-this.getContentSize().width / 2 - inflate, -this.getContentSize().height / 2 - inflate),
                cc.p(-this.getContentSize().width / 2 - inflate, this.getContentSize().height / 2 + inflate)
            ];
            for (var i = 0; i < rotatingConnerArray.length; i ++) {
                if (cc.pDistance(rotatingConnerArray[i], nodeLocation) < 10) {
                    this._isRotating = true;
                    break;
                }
            }

            if (!this._isRotating) {
                var scalingConnerArray = [
                    cc.p(this.getContentSize().width / 2 + inflate, this.getContentSize().height / 2 + inflate),
                    cc.p(this.getContentSize().width / 2 + inflate, -this.getContentSize().height / 2 - inflate)
                ];
                for (var i = 0; i < scalingConnerArray.length; i ++) {
                    if (cc.pDistance(scalingConnerArray[i], nodeLocation) < 10) {
                        this._isScaling = true;
                        break;
                    }
                }
            }
        }
    },
    delegateTouchMoved:function(touch, event) {
        if (!this.isSelected()) {
            return;
        }
        var location = touch.getLocation();
        if (this._isEditVertex) {
            this._processUpdateVertex(location);
        }
        else if (this._isRotating) {
            this._processRotate(touch.getDelta());
        }
        else if (this._isScaling) {
            this._processScale(touch.getDelta());
        }
        else {
            this._processMove(location);
        }
    },
    delegateTouchEnded:function(touch, event) {
        if (!this.isSelected()) {
            return;
        }
        this._isEditVertex = false;
        this._isRotating = false;
        this._isScaling = false;
        this._editVertexIndex = -1;
    },
    delegateTouchCanceled:function() {
        if (!this.isSelected()) {
            return;
        }
    },
    delegateTouchLongPressed:function(location) {
        if (!this.isSelected() || this._isRotating || this._isScaling) {
            return;
        }
        var selectedVertexIndex = this._getVertexIndexFromTouch(location);
        if (selectedVertexIndex != -1) {
            this._isEditVertex = true;
            this._editVertexIndex = selectedVertexIndex;
            this._processRemoveVertex();
        }
        else {
            this._processAddVertex(location);
        }
    },
    delegateTouchSelect:function() {
        this._isDebugDrawOn = true;
        if (this._debugDrawNode) {
            this._debugDrawNode.setVisible(true);
        }
        if (this._debugLabelNode) {
            this._debugLabelNode.setVisible(true);
        }
        this._debugDraw();
    },
    delegateTouchDeselect:function() {
        this._isDebugDrawOn = false;
        if (this._debugDrawNode) {
            this._debugDrawNode.setVisible(false);    
        }
        if (this._debugLabelNode) {
            this._debugLabelNode.setVisible(false);
        }
    },
    _processMove:function(location) {
        var deltaPosition = cc.pSub(location, this.getPosition());
        deltaPosition = cc.pSub(deltaPosition, this._editGrabPosition);
        this.setPosition(cc.pAdd(this.getPosition(), deltaPosition));
        if (this._delegate && this._delegate.moveCallback) {
            this._delegate.moveCallback(this);
        }
    },
    _processAddVertex:function(location) {
        var transformed = this._invertTransformedPosition(location);
        this.addVertex(transformed);
        if (this._delegate && this._delegate.vertexUpdateCallback) {
            this._delegate.vertexUpdateCallback(this, this._editVertexIndex);
        }
    },
    _processRemoveVertex:function() {
        this.removeVertex(this._editVertexIndex);
        if (this._delegate && this._delegate.vertexUpdateCallback) {
            this._delegate.vertexUpdateCallback(this, this._editVertexIndex);
        }
    },
    _processUpdateVertex:function(newPosition) {
        var oldPosition = cc.p(this._vertexArray[this._editVertexIndex]);
        var transformed = this._invertTransformedPosition(newPosition);
        this.updateVertex(this._editVertexIndex, transformed);
        if (this._delegate && this._delegate.vertexUpdateCallback) {
            this._delegate.vertexUpdateCallback(this, this._editVertexIndex, oldPosition, transformed);
        }
    },
    _processRotate:function(delta) {
        var angle = (delta.y > 0 ? 5 : -5);
        this.setRotation(this.getRotation() + angle);
        if (this._delegate && this._delegate.rotateCallback) {
            this._delegate.rotateCallback(this);
        }
    },
    _processScale:function(delta) {
        var scale = (delta.y > 0 ? 0.01 : -0.01);
        this.setScale(this.getScale() + scale);
        if (this._delegate && this._delegate.scaleCallback) {
            this._delegate.scaleCallback(this);
        }  
    },
    dump:function() {
        var output = JSON.stringify(this._vertexArray, null, 4);
        output = output.replace(/\"x\": /g, "").replace(/\"y\": /g, "").replace(/{/g, "cc.p(").replace(/}/g, ")");
        cc.log(output);
    },
    _debugDraw:function() {
        if (!this._debugDrawNode) {
            this._debugDrawNode = new cc.DrawNode();
            this.addChild(this._debugDrawNode, 99);
        }
        if (!this._debugLabelNode) {
            this._debugLabelNode = new cc.Node();
            this.addChild(this._debugLabelNode, 99);
        }
        this._debugDrawNode.clear();
        this._debugDrawNode.setPosition(0, 0);
        this._debugLabelNode.removeAllChildren(true);
        // position
        var centerInNode = cc.p(
            this.getContentSize().width * this.getAnchorPoint().x, 
            this.getContentSize().height * this.getAnchorPoint().y
        );
        this._debugDrawNode.drawDot(centerInNode, 4, cc.color.GREEN);
        // boundingBox
        var inflate = 6;
        this._debugDrawNode.drawRect(
            cc.p(-inflate, -inflate),
            cc.p(this.getContentSize().width + inflate, this.getContentSize().height + inflate),
            cc.color(0, 0, 0, 0),
            4,
            cc.color(0, 0, 255, 255)
        );
    },
});
ssr.addon(ssr.EditableGeometryNode.prototype, ssr.Addon.Touchable);
